import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state: () => ({
    user: JSON.parse(localStorage.getItem("currentUser")) || null,
    isLoggedIn: localStorage.getItem("isLoggedIn") === "true" || false
  }),
  actions: {
    setUser(userData) {
      this.user = userData;
      this.isLoggedIn = true;
      localStorage.setItem("currentUser", JSON.stringify(userData));
      localStorage.setItem("isLoggedIn", "true");
    },
    clearUser() {
      this.user = null;
      this.isLoggedIn = false;
      localStorage.removeItem("currentUser");
      localStorage.removeItem("isLoggedIn");
    },
      // 获取当前用户角色
      getUserRole() {
        return this.user ? this.user.role : null;
      },
      // 判断是否为管理员
      isAdmin() {
        return this.isLoggedIn && this.user.role === "admin";
      },
      // 判断是否为买家
      isBuyer() {
        return this.isLoggedIn && this.user.role === "buyer";
      },
      // 判断是否为卖家
      isSeller() {
        return this.isLoggedIn && this.user.role === "seller";
      },
    },
  },
  {
    persist: {
      enabled: true,
      strategies: [
        {
          key: "user",
          storage: localStorage,
          paths: ["user", "isLoggedIn"]
        }
      ]
    }
  }
);